package cn.xzchain.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author lihang
 * @date 2018/9/6.
 * @description
 */
@Component
@Slf4j
public class RedisService<K,V> {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 设置键值对
     * @param key
     * @param value
     */
    public void set(K key, V value){
        try {
            redisTemplate.opsForValue().set(key,value);
        }catch (Exception e){
            log.error("[redis set error! key:{}]",key,e);
        }
    }

    /**
     * 设置带超时时间的key
     * @param key
     * @param value
     * @param timeout 秒
     */
    public void setWhitExpire(K key, V value,long timeout){
        try {
            redisTemplate.opsForValue().set(key,value,timeout, TimeUnit.SECONDS);
        }catch (Exception e){
            log.error("[redis set error! key:{}]",key,e);
        }
    }

    /**
     * 根据key获取值
     * @param key
     * @return
     */
    public Object get(K key){
        try {
            return redisTemplate.opsForValue().get(key);
        }catch (Exception e){
            log.error("[redis get error! key:{}]",key,e);
            return null;
        }
    }
}
